<template>
  <div>
    <div ref="container" style="max-height: 70vh; overflow: auto; border: 1px solid #eee; padding: 12px;">
      <div v-for="(url, idx) in imageUrls" :key="idx" style="margin-bottom: 16px;">
        <img
          :data-src="url"
          :alt="`img-${idx}`"
          ref="lazyImgs"
          width="400"
          height="300"
          style="display:block; width: 400px; height: 300px; background:#f6f7f8; border-radius: 4px; object-fit: cover;"
          src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='300'%3E%3Crect width='100%25' height='100%25' fill='%23f0f0f0'/%3E%3Ctext x='50%25' y='50%25' dominant-baseline='middle' text-anchor='middle' fill='%23bbb' font-size='20'%3ELoading...%3C/text%3E%3C/svg%3E"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'

// 准备若干图片地址（可根据需要替换为自己的资源）
const localAsset = new URL('../assets/effect-item.png', import.meta.url).href
const imageUrls = ref(Array.from({ length: 20 }, (_, i) => localAsset))

const container = ref(null)
const lazyImgs = ref([])
let observer = null

onMounted(async () => {
  await nextTick()
  // 创建 IntersectionObserver
  observer = new IntersectionObserver(onIntersect, {
    root: container.value,
    rootMargin: '0px 0px 200px 0px',
    threshold: 0.01,
  })

  // 观察所有图片元素
  lazyImgs.value.forEach((imgEl) => {
    if (imgEl) observer.observe(imgEl)
  })
})

onBeforeUnmount(() => {
  if (observer) {
    observer.disconnect()
    observer = null
  }
})

function onIntersect(entries) {
  console.log('回调函数执行',entries);
  
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      const img = entry.target
      const realSrc = img.getAttribute('data-src')
      if (realSrc) {
        img.src = realSrc
        img.removeAttribute('data-src')
      }
      if (observer) observer.unobserve(img)
    }
  })
}

</script>